<template>
  <div>
    <div class="userBox">
      <el-tabs v-model="activeName" @tab-click="handleClick" class="head">
        <!-- 登陆表单 -->
        <el-tab-pane label="登陆" name="first">
          <div class="loginBox">
            <el-card class="loginCard" ref="loginCardRef">
              <el-form
                :model="loginForm"
                status-icon
                :rules="loginRules"
                ref="loginFormRef"
                label-width="100px"
                class="loginForm"
              >
                <el-form-item label="账号" prop="username">
                  <el-input type="text" v-model="loginForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input
                    type="password"
                    v-model="loginForm.password"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                  <el-input type="code" v-model="code" style="width: 63%">
                  </el-input>
                  <el-button
                    @click="postLoginCode()"
                    style="
                      padding-left: 8px;
                      padding-right: 8px;
                      margin-left: 10px;
                    "
                    >获取验证码</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitLoginForm()"
                    >登陆</el-button
                  >
                  <el-button @click="resetForm()">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </el-tab-pane>

        <!-- 注册表单 -->
        <el-tab-pane label="注册" name="second">
          <div class="registerBox">
            <el-card class="registerCard" ref="registerCardRef">
              <el-form
                :model="registerForm"
                status-icon
                :rules="registerRules"
                ref="registerFormRef"
                label-width="100px"
                class="registerForm"
              >
                <el-form-item label="昵称" prop="nickname">
                  <el-input
                    type="text"
                    v-model="registerForm.nickname"
                  ></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="username">
                  <el-input
                    type="text"
                    v-model="registerForm.username"
                  ></el-input>
                </el-form-item>

                <el-form-item label="密码" prop="password">
                  <el-input
                    type="password"
                    v-model="registerForm.password"
                    autocomplete="off"
                  ></el-input>
                </el-form-item>

                <el-form-item label="真实姓名" prop="realName">
                  <el-input
                    type="text"
                    v-model="registerForm.realName"
                  ></el-input>
                </el-form-item>

                <el-form-item label="学号" prop="studentNum">
                  <el-input
                    type="text"
                    v-model="registerForm.studentNum"
                  ></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                  <el-input type="text" v-model="registerForm.email"></el-input>
                </el-form-item>

                <el-form-item label="认证材料" prop="material">
                  <el-upload
                    class="upload-demo"
                    action="#"
                    :before-remove="beforeRemove"
                    multiple
                    :before-upload="beforeUpload"
                    :limit="1"
                    :file-list="registerForm.material"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">
                      只能上传jpg/png文件，且不超过500kb
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="验证码" prop="code">
                  <el-input type="code" v-model="code" style="width: 63%">
                  </el-input>
                  <el-button
                    @click="postRegisterCode()"
                    style="
                      padding-left: 8px;
                      padding-right: 8px;
                      margin-left: 10px;
                    "
                    >获取验证码</el-button
                  >
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="submitRegisterForm()"
                    >注册</el-button
                  >
                  <el-button @click="resetForm()">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
export default {
  layout: "login",
  data() {
    var checkPhone = (rules, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (!this.isCellPhone(value)) {
        callback(new Error("非法用户名"));
      } else {
        callback();
      }
    };
    var checkStudentNum = (rules, value, callback) => {
      if (value === "") {
        callback(new Error("请输入学号"));
      } else if (!this.isStudentNum(value)) {
        callback(new Error("请输入正确的学号"));
      } else {
        callback();
      }
    };
    return {
      activeName: "first",
      //登录表单
      loginForm: {
        username: "",
        password: "",
      },
      //表单验证规则对象
      loginRules: {
        username: [{ required: true, validator: checkPhone, trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 9, message: "长度至少9位", trigger: "blur" },
        ],
      },
      //注册表单
      registerForm: {
        nickname: "",
        username: "",
        password: "",
        realName: "",
        studentNum: "",
        email: "",
        material: [
          {
            name: "111",
            url: "http://192.168.9.128:8888/group1/M00/00/00/wKgJgGI22DGAIJzNAADcDH6cdx0811.jpg",
          },
        ],
      },

      registerRules: {
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 4,
            max: 16,
            message: "长度在 4 到 16 个字符",
            trigger: "blur",
          },
        ],
        username: [{ required: true, validator: checkPhone, trigger: "blur" }],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 9, message: "长度至少9位", trigger: "blur" },
        ],
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        studentNum: [
          { required: true, validator: checkStudentNum, trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur"] },
        ],
        material: [
          { required: true, message: "请上传实名认证材料", trigger: "blur" },
        ],
      },
      //验证码
      code: "",
    };
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    submitLoginForm() {
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          let data = {
            username: this.loginForm.username,
            password: this.loginForm.password,
            code: this.code,
          };
          let res = await this.$axios.$post("/fgUser/login", data);
          console.log(res);
          if (res.code / 100 == 4) {
            return this.$message.error("登录失败");
          }
          this.$message.success("登录成功");
        } else {
          this.$message.error("用户名密码不饿能为空");
          return false;
        }
      });
    },
    submitRegisterForm() {
      this.$refs.registerFormRef.validate(async (valid) => {  
        if (valid) {
          let data = {
            nickname: this.registerForm.nickname,
            username: this.registerForm.username,
            password: this.registerForm.password,
            realName: this.registerForm.realName,
            studentNum: this.registerForm.studentNum,
            email: this.registerForm.email,
            material: this.registerForm.material[0].url,
            code: this.code,
          };
          let res = await this.$axios.$post("/fgUser/register", data);
          console.log(res);
          if (res.code == 400) {
            return this.$message.error("注册失败");
          }
          this.$message.success("注册成功");
          this.code = "";
        } else {
          this.$message.warning("请检查注册信息是否合法");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    isCellPhone(val) {
      if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(val)) {
        return false;
      } else {
        return true;
      }
    },
    isStudentNum(val) {
      if (!/^(1|2)(0|1|2|3|4|5|6|7|8|9)\d{9}$/.test(val)) {
        return false;
      } else {
        return true;
      }
    },
    postLoginCode() {
      //async 异步
      this.$refs.loginFormRef.validate(async (valid) => {
        if (valid) {
          let res = await this.$axios.$post(
            "/fgUser/sendLoginVerificationCode",
            this.loginForm
          );
          console.log(res);
          if (res.code == 727) {
            return this.$message.error(res.msg);
          } else if (res.code == 400) {
            return this.$message.error("发送失败");
          }
          this.$message.success("发送成功");
        } else {
          this.$message.warning("请检查用户名和密码是否合法");
          return false;
        }
      });
    },
    postRegisterCode() {
      console.log(this.$refs);
      this.$refs.registerFormRef.validate(async (valid) => {
        if (valid) {
          let data = {
            nickname: this.registerForm.nickname,
            username: this.registerForm.username,
            password: this.registerForm.password,
            realName: this.registerForm.realName,
            studentNum: this.registerForm.studentNum,
            email: this.registerForm.email,
            material: this.registerForm.material[0].url,
          };
          let res = await this.$axios.$post(
            "/fgUser/sendRegVerificationCode",
            data
          );
          console.log(res);
          if (res.code == 727) {
            return this.$message.error("请勿频繁发送验证码,稍后再试!");
          } else if (res.code == 400) {
            return this.$message.error("发送失败");
          }
          this.$message.success("发送成功");
        } else {
          this.$message.warning("请检查注册信息是否合法");
          return false;
        }
      });
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    handleSuccess(res, file) {
      this.registerForm.material[2] = URL.createObjectURL(file.raw);
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      this.$confirm("是否上传该文件？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios.$post(
            "/upload/uploadPicture",
            this.registerForm.material[1].url
          );
          console.log(res);
          if (res.data != 200) {
            return this.$message({
              type: "error",
              message: "上传失败",
            });
          }
          this.$message({
            type: "success",
            message: "上传成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消上传",
          });
        });
      return isLt2M;
    },
  },
};
</script>

<style lang="scss" scope>
body {
  background-image: url(../../assets/img/loginbg.webp);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-attachment: fixed;
}
.userBox {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 500px;
  padding: 40px;
  padding-top: 10px;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.338);
  box-sizing: border-box;
  box-shadow: 0 15px 25px rgba(0, 0, 0, 0.482);
  border-radius: 10px;
  .head {
    color: #fff;
    .loginBox {
      position: relative;
    }
    .registerBox {
      position: relative;
      .el-upload__tip {
        color: crimson;
      }
    }
    .el-tabs__item {
      color: #fff;
      font-size: 20px;
    }
    .el-tabs__active-bar {
      width: 35px;
    }
    .el-card {
      background-color: rgba(0, 0, 0, 0);
      color: #fff;
      border: none;
      .el-card__body {
        margin-bottom: -35px;
      }
    }
    .el-form-item__label {
      color: #fff;
    }
    .el-form-item {
      margin-left: -40px;
    }
  }
}
</style>
